package com.github.boluo1230.wechat.dao.impl;

import com.github.boluo1230.wechat.dao.WxUserDao;
import com.github.boluo1230.wechat.entity.WxUser;
import com.mongodb.client.result.UpdateResult;
import lombok.AllArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

/**
 * @author Code Farmer
 * @date 2019/10/14 15:04
 */
@Repository
@AllArgsConstructor
public class WxUserDaoImpl implements WxUserDao {

    private final MongoTemplate mongoTemplate;

    public void insert(WxUser wxUser, String appId) {
        mongoTemplate.insert(wxUser, "wx_user_" + appId);
    }

    public long unSubscribe(String openId, String appId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(openId));
        Update update = new Update();
        update.set("subscribe", 0);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, "wx_user_" + appId);
        return updateResult.getModifiedCount();
    }

}
